$(function () {
    var $tbWork = $('#tbWork'), $pager = $('#tbWorkPager');
    var $tbGood = $('#tbGood'), $pager = $('#tbGoodPager');

    // 调出模态框的时候去加载数据
    $('#modal-tbWork').on('show.bs.modal', function (e) {
        //加载数据
        $tbWork.jqGrid({
            url: addCarSingleForm_urls.getWork,
            datatype: 'json',
            mttype: 'post',
            colNames: ['工单号', '车牌号', '客户名', '操作'],
            colModel: [
                {name: 'num', index: 'num', width: '130', align: 'center'},
                {name: 'car_num', index: 'car_num', width: '120', align: 'center'},
                {name: 'client_name', index: 'client_name', width: '150', align: 'center'},
                {
                    name: 'num', index: 'num', width: '100', align: 'center',
                    formatter: function (value, options, obj) {
                        return '<a style="cursor:pointer;" onclick="addCarSingleForm.chooseWork(\'' + value + '\',\'' + obj.car_num + '\',' + obj.id + ');">选择</a>';
                    }
                },
            ],
            height: 'auto',
            pager: '#tbWorkPager',
            // viewrecords: true,
            rowNum: 10,
            rowList: [10, 20, 40],
            autowidth: true
        });
        // 隐藏水平方向滚动条
        $tbWork.closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
    });

    $('#modal-tbGood').on('show.bs.modal', function (e) {
        //加载数据
        $tbGood.jqGrid({
            url: addCarSingleForm_urls.getGood,
            datatype: 'json',
            mttype: 'post',
            colNames: ['编号', '名称', '单价', '数量', '操作'],
            colModel: [
                {name: 'num', index: 'num', width: '130', align: 'center'},
                {name: 'name', index: 'name', width: '120', align: 'center'},
                {name: 'price', index: 'price', width: '100', align: 'center'},
                {name: 'storage', index: 'storage', width: '50', align: 'center'},
                {
                    name: 'num', index: 'num', width: '100', align: 'center',
                    formatter: function (value, options, obj) {
                        console.log(options);
                        return '<a id="choose' + value + '" style="cursor:pointer;" onclick="addCarSingleForm.chooseGood(\'' + value + '\',\'' + obj.name + '\',\'' + obj.price + '\',' + obj.storage + ',' + options.rowId + ',this);">选择</a>';
                    }
                },
            ],
            height: 'auto',
            pager: '#tbGoodPager',
            // viewrecords: true,
            rowNum: 10,
            rowList: [10, 20, 40],
            autowidth: true
        });
        // 隐藏水平方向滚动条
        $tbGood.closest(".ui-jqgrid-bdiv").css({"overflow-x": "hidden"});
    });
});
addCarSingleForm = {
    // 查询客户
    search: function () {
        var $fmQuery = $('.fmWorkQuery-hook');
        var param = ittaoli.serializeObject($fmQuery);
        $('#tbWork').jqGrid('setGridParam', {
            postData: {q: JSON.stringify(param)},
            page: 1
        }).trigger("reloadGrid");
    },
    // 清空查询条件
    searchNull: function () {
        $('.fmWorkQuery-hook input').val('');
        var param = {};
        $('#tbWork').jqGrid('setGridParam', {
            postData: {q: JSON.stringify(param)},
            page: 1
        }).trigger("reloadGrid");
    },
    // 选择客户
    chooseWork: function (num, car_num, id) {
        $('#fmWork input[name=id]').val(id);
        $('#fmWork input[name=num]').val(num);
        $('#fmWork input[name=car_num]').val(car_num);
        $('#modal-tbWork').modal('hide');
    },
    //保存产品零件数据(添加产品模态框的保存事件)
    addGood: function (obj) {
        $(obj).button('loading');
        // business logic...
        var param = ittaoli.serializeObject($('.fmGoodAdd-hook'));
        param.id = 0;
        if (param.num == '') {
            bootbox.alert('请填写产品编号');
            return;
        }
        if (param.name == '') {
            bootbox.alert('请填写产品名称');
            return;
        }
        if (param.storage == '') {
            bootbox.alert('请填写产品数量');
            return;
        }
        if (!ittaoli.regs.int.test(param.storage)) {
            bootbox.alert('产品数量格式不对哦！');
            return;
        }
        if (param.price == '') {
            bootbox.alert('请填写产品单价');
            return;
        }
        console.log(param);
        $.post(addCarSingleForm_urls.addGood, {param: JSON.stringify(param)}, function (data) {
            if (data > 0) {
                $('#tbGood').jqGrid('setGridParam', {
                    page: 1
                }).trigger("reloadGrid");
                $('.fmGoodAdd-hook')[0].reset();

                // $('#modal-fmGood').modal('hide');
            } else {
                bootbox.alert('保存失败！');
            }
            $(obj).button('reset');
        })
    },
    // 查询产品
    searchGood: function () {
        var $fmQuery = $('.fmGoodQuery-hook');
        var param = ittaoli.serializeObject($fmQuery);
        $('#tbGood').jqGrid('setGridParam', {
            postData: {q: JSON.stringify(param)},
            page: 1
        }).trigger("reloadGrid");
    },
    // 清空产品查询条件
    searchNullGood: function () {
        $('.fmGoodQuery-hook input').val('');
        var param = {};
        $('#tbGood').jqGrid('setGridParam', {
            postData: {q: JSON.stringify(param)},
            page: 1
        }).trigger("reloadGrid");
    },
    // 选择产品
    chooseGood: function (num, name, price, nums, rowId, obj) {
        $(obj).hide();
        var $tbGood = $('#tbGood');
        var storage = $tbGood.jqGrid('getCell', rowId, 3);
        // console.log(storage);
        if (storage > 0) {
            // $tbGood.jqGrid('setCell',rowId,3,--storage);
            var rows=$('.tbServerSelected tbody tr').length-1;
            // console.log(rows);
            var tr = '<tr><td>' + num + '</td><td>' + name + '</td><td>' + price + '</td>';
            tr += '<td rowId="' + rows + '" max="' + nums + '" price="' + price + '"><a class="minus' + rows + ' btn btn-danger btn-xs" onclick="addCarSingleForm.minus(this,\'' + $(obj).attr('id') + '\');"><i class="fa fa-minus  bigger-110"></i></a><span>1</span><a class="plus' + rows + ' btn btn-info btn-xs" onclick="addCarSingleForm.plus(this);"><i class="fa fa-plus  bigger-110"></i></a></td>';
            tr += '<td class="sum">' + price + '</td>';
            tr += '</tr>';
            var len = $('.tbServerSelected .total').length;
            if (len == 0) {
                tr += '<tr><td></td><td></td><td></td><td>总计：</td><td class="total"></td></tr>';
                $('.tbServerSelected').append(tr);
            } else {
                $('.tbServerSelected .total').parent().before(tr);
            }
            var total = addCarSingleForm.calcTotal();
            $('.total').text(total);
        } else {
            bootbox.alert("该产品已无库存！");
        }
    },
    // 产品数量增加
    plus: function (obj) {
        var rowId = $(obj).parent().attr('rowId');
        var max = $(obj).parent().attr('max');
        var price = $(obj).parent().attr('price');
        var $tbGood = $('#tbGood');
        var nowNum = $(obj).prev('span').text();
        if (parseInt(nowNum) < parseInt(max)) {
            nowNum++;
            $('.plus' + rowId).prev('span').text(nowNum);

            //小计
            $('.plus' + rowId).parent().next('td').text(price * nowNum);
            //总计
            var total = addCarSingleForm.calcTotal();
            $('.total').text(total);
        } else {
            bootbox.alert('已超过最大库存！');
        }
    },
    // 产品数量减少
    minus: function (obj, id) {
        var rowId = $(obj).parent().attr('rowId');
        var max = $(obj).parent().attr('max');
        var $tbGood = $('#tbGood');
        var price = $(obj).parent().attr('price');

        var nowNum = $(obj).next('span').text();
        if (parseInt(nowNum) > 1) {
            nowNum--;
            $('.minus' + rowId).next('span').text(nowNum);

            // 小计
            $('.minus' + rowId).parent().next('td').text(price * nowNum);
            //总计
            var total = addCarSingleForm.calcTotal();
            $('.total').text(total);
        } else {
            bootbox.confirm("目前数量为1，再减会删除该项，确定继续？", function (result) {
                if (result) {
                    $(obj).parent().parent().remove();
                    $('#' + id).show();
                }
            });
            //总计
            var total = addCarSingleForm.calcTotal();
            $('.total').text(total);
        }

    },
    //确定服务选项
    confirmServe: function () {
        // var html=$('.tbServerSelected').html();
        // $('#tbServerSelected').html(html);
        $('#modal-tbGood').modal('hide');
    },
    // 计算总价
    calcTotal: function () {
        var total = 0;
        var cover = "本次为您服务的项目";
        $($('.tbServerSelected')[1]).find('.sum').each(function (index, item) {
            var goodsName = $(item).prev().prev().prev().text();
            cover += "，" + goodsName + "质保期为__年/KM";

            var price = parseFloat($(item).text());
            total += price;
        });
        $("textarea[name=cover]").text(cover + "。");
        return total;
    },
    // 保存工单数据
    saveWork: function (obj) {
        var param = ittaoli.serializeObject($('#fmWork'));
        if (!param.id || param.id == 0) {
            bootbox.alert('请先选择工单！');
            return;
        }
        var tbServer = [];
        var $trs = $('.tbServer tr');
        for (var i = 1, len = $trs.length - 1; i < len; i++) {
            tbServer.push({
                gnum: $trs.eq(i).find('td').eq(0).text(),
                name: $trs.eq(i).find('td').eq(1).text(),
                price: $trs.eq(i).find('td').eq(2).text(),
                num: $trs.eq(i).find('td').eq(3).text(),
                sum: $trs.eq(i).find('td').eq(4).text()
            });
        }

        // return;
        $(obj).button('loading');

        $.post(addCarSingleForm_urls.addWork, {
            param: JSON.stringify(param),
            servers: JSON.stringify(tbServer)
        }, function (data) {
            if (data > 0) {
                bootbox.alert("保存成功！");
                setTimeout(function () {
                    location.href = addCarSingleForm_urls.indexServer;
                }, 1000);
            } else {
                bootbox.alert('保存失败！');
            }
            $(obj).button('reset');
        })
    }
};